#!/bin/sh
FULLBK_D="Sunday"
FULLBK_H="04"
DBPATH="/var/lib/mysql"
DB="stable_athena"
DBBINLOG="athenabinlog"
DBU="root"
DBH="localhost"
BKPATH="/var/www/backup"
BKPATH2="/var/www/backup/older"

if [ ! -d $BKPATH ]; then
	mkdir $BKPATH
fi


if [ `date +%A` = $FULLBK_D -a `date +%H` = $FULLBK_H -o "$1" = "bkfull" ]; then
	PRE="athena-bkfull"
	EXT="sql"
	NOW=`date +%Y-%m-%d`
	DBF=$PRE-$NOW.$EXT

	echo 
	echo "Automatic crontab to back up database."
	echo 
	echo "[INFO] Date: `date`"
	echo "[INFO] Host: `hostname`"
	echo "[INFO] User: `whoami`"
	#echo "[INFO] Server: `ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | cut -d: -f2 | awk '{ print $1}'`"
	echo "[INFO] Database: $DB"

	echo
	# Perform full back up
	echo "[INFO] Starting full back-up..."
	mysqldump -u $DBU -h $DBH --databases $DB --quick --flush-logs --delete-master-logs --add-drop-table --lock-all-tables > $DBPATH/$DBF
	# Remove old zip-backup file
	rm -f $DBPATH/*.bz2	
	# Zip new back up file
	bzip2 $DBPATH/$DBF

	echo "[INFO] Complete full back-up"

	# Make older dir if not exist	
	if [ ! -d $BKPATH2 ]; then
		mkdir $BKPATH2
	fi
	# Remove all older back-up files
	rm -f $BKPATH2/*.bz2
	# Move current back up files to older dir
	echo "[INFO] Moving previous back-up files..."
	c=`ls -l $BKPATH/*.bz2 2>/dev/null | wc -l`
	if [ $c > 0 ]; then
		mv $BKPATH/*.bz2 $BKPATH2
	fi	
	
	echo "[INFO] Copying newest back-up files..."
	echo
	echo "[INFO] Current back-up files are available at $BKPATH"
	echo "[INFO] Previous back-up files are available at $BKPATH2"
else
	mysqladmin -u $DBU flush-logs
fi

# Flush new bin log to record DB changes & bzip2 the old ones
newestlog=`ls -d $DBPATH/$DBBINLOG.?????? | sed 's/^.*\.//' | sort -g | tail -n 1`
for file in `ls $DBPATH/$DBBINLOG.??????`
do
        if [ "$DBPATH/$DBBINLOG.$newestlog" != "$file" ]; then
                bzip2 "$file"
        fi
done
cp -u $DBPATH/*.bz2 $BKPATH
